<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/28
 * Time: 15:20
 */

namespace wxpay;

use app\index\controller\Wechat;
use think\facade\Cache;
use think\facade\Log;


header("Content-Type:text/html; charset=utf-8");

class Wxsend
{
    private static $appid;
    private static $appsecret;
    private static $temp_verify_data;

    function __construct()
    {
        $conf=config('wechat.');
        self::$appid = 'wxe4b77d2f0f456b9b';      // 开发者ID(AppID)
        self::$appsecret = '98610d87a12e0169eec933fca8f85234';  // 开发者密码(AppSecret)
        self::$temp_verify_data =$conf['wechat_notice']['temp_verify_data'];  // 开发者密码(AppSecret)
    }

    // 微信授权地址
    public static function getAuthorizeUrl($url)
    {
        $url_link = urlencode($url);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . self::$appid . "&redirect_uri={$url_link}&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
    }

    // 获取TOKEN
    public static function getToken()
    {
        $wechat = new Wechat();
        $wx_token = $wechat->GetToken();
        return $wx_token;

        $wx_token = Cache::get('access_token');

        if(empty($wx_token)){
            $urla = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::$appid . "&secret=" . self::$appsecret;
            $outputa = self::curlGet($urla);
            $result = json_decode($outputa, true);
            Log::write('access_token：'.json_encode($result),'error');
            Cache::set('access_token', $result['access_token'],7000);
            return $result['access_token'];
        }else{
            return $wx_token;
        }


    }

    /**
     * getUserInfo 获取用户信息
     * @param  string $code 微信授权code
     * @param  string $weiwei_token Token
     * @return array
     */
    public static function getUserInfo($code, $weiwei_token)
    {
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . self::$appid . "&secret=" . self::$appsecret . "&code={$code}&grant_type=authorization_code";
        $access_token_json = self::curlGet($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        $openid = $access_token_array['openid'];
        $new_access_token = $weiwei_token;

        //全局access token获得用户基本信息
        $userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$new_access_token}&openid={$openid}";
        $userinfo_json = self::curlGet($userinfo_url);
        $userinfo_array = json_decode($userinfo_json, true);
        return $userinfo_array;
    }

    /**
     * @param  string $topcolor 模板内容字体颜色，不填默认为黑色
     * @return array
     */
    public static function pushMessage($data = [], $topcolor = '#0000')
    {
        $template = [
            'touser' => $data['openid'],
            'template_id' => $data['template_id'],
            'url' => $data['url_link'],
            'topcolor' => $topcolor,
            'data' => $data['data']
        ];
        $json_template = json_encode($template);
        if (!self::getToken()) {
            return Log::write('pushMessage_token:' . json_encode(self::getToken()), 'error');
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . self::getToken();
        $result = self::curlPost($url, urldecode($json_template));
        $resultData = json_decode($result, true);
        Log::write('推送参数：'.json_encode($template).'推送结果:'.json_encode($resultData),'error');
        return $resultData;
    }

    /**
     * addLog 日志记录
     * @param string $log_content 日志内容
     */
    public static function addLog($log_content = '')
    {
        $data = "";
        $data .= "DATE: [ " . date('Y-m-d H:i:s') . " ]\r\n";
        $data .= "INFO: " . $log_content . "\r\n\r\n";
        file_put_contents('/wechat.log', $data, FILE_APPEND);
    }

    /**
     * 发送get请求
     * @param string $url 链接
     * @return bool|mixed
     */
    private static function curlGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $output;
    }

    /**
     * 发送post请求
     * @param string $url 链接
     * @param string $data 数据
     * @return bool|mixed
     */
    private static function curlPost($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * get_page_url 获取完整URL
     * @return url
     */
    function get_page_url($type = 0)
    {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == 'on') {
            $pageURL .= 's';
        }
        $pageURL .= '://';
        if ($type == 0) {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }
        return $pageURL;
    }


    public function sendMsg($openid='',$type='',$keyword1='',$keyword2='',$keyword3='',$keyword4='',$keyword5='',$url='')
    {
        $weiwei_token = $this->getToken(); // 获取微信token
        if (!$weiwei_token) {
            return Log::write('token:' . json_encode($weiwei_token), 'error');
        }
        $template = self::template($type,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5);
        $template_id = self::templateId($type);

        if($type==5){
            $link = 'http://wx3.xnm3000.cn/project/login';
        }elseif($type==7){
            $link = 'https://links.xnm3000.cn/pubno/#/pages/user/uservip';
        }elseif($type==2){
            $link = 'http://wx3.xnm3000.cn/project/myActiveDetail1?id='.$keyword4;
        }elseif($type==8) {
            $link = 'http://wx3.xnm3000.cn/project/activityDetail?id=' . $keyword4;
        }elseif($type==10) {
            $link = 'http://wx3.xnm3000.cn/project/node_development';
        }elseif($type==11){
            $acc = PartnerAccountModel::where(['openid'=>$openid,'state'=>0])->find();
            $link = 'http://wx3.xnm3000.cn/project/omCenter?type=1&id='.$acc['id'];
        }else{
            $link = 'https://links.xnm3000.cn/pubno'.$url;
        }
        # 公众号消息推送
        $data = self::pushMessage([
            'openid' => $openid, // 用户openid
            'access_token' => $weiwei_token,
            'template_id' => $template_id, // 填写你自己的消息模板ID
            'data' => $template,
            'url_link' => $link // 消息跳转链接
        ]);

        return $data;
    }


    /**
     * 消息模板
     *
     */
    public static function template($type='',$keyword1='',$keyword2='',$keyword3='',$keyword4='',$keyword5=''){
        if($type == 1){
            return $template =[ // 购买会员模板消息内容
                'productType' => ['value' => urlencode("商品名"), 'color' => "#0000"],
                'name' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'number' => ['value' => urlencode($keyword2), 'color' => '#FF0000'],
                'expDate' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }elseif($type == 2){
            return $template =[ // 活动报名模板消息内容
                'first' => ['value' => urlencode('您已报名成功'), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'keyword2' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电".$keyword5."联系我们。"), 'color' => '#0000']
            ];
        }elseif($type == 3){
            if($keyword2=='通过' || ($keyword2=='回复')){
                $color = '#0000FF';
            }else{
                $color = '#FF0000';
            }
            return $template =[ // 社群审核模板消息内容
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => $color],
                'keyword2' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword4), 'color' => '#0000'],
                'remark' => ['value' => urlencode($keyword5), 'color' => '#0000']
            ];
        }elseif($type == 4){
            return $template =[ // 附件付费
                'first' => ['value' => urlencode("您好，附件付费成功"), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'keyword2' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword3), 'color' => '#FF0000'],
                'keyword4' => ['value' => urlencode($keyword4), 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }elseif($type == 5){
            return $template =[ // 运营中心推荐业务员
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => '#FF0000'],
                'keyword2' => ['value' => urlencode($keyword3), 'color' => '#FF0000'],
                'keyword3' => ['value' => urlencode($keyword4), 'color' => '#0000'],
                'remark' => ['value' => urlencode("赶快去发展业务吧！"), 'color' => '#0000']
            ];
        }elseif($type == 6){
            return $template =[ // 运营中心推荐业务员
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => '#FF0000'],
                'keyword2' => ['value' => urlencode($keyword3), 'color' => '#FF0000'],
                'keyword3' => ['value' => urlencode($keyword4), 'color' => '#0000'],
                'remark' => ['value' => urlencode("赶快去发展业务吧！"), 'color' => '#0000']
            ];
        }elseif($type == 7){
            return $template =[ // 会员到期提醒
                'first' => ['value' => urlencode('您好，您的云链路VIP已过期'), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'keyword2' => ['value' => urlencode($keyword2), 'color' => '#FF0000'],
                'remark' => ['value' => urlencode("为了不影响功能的正常使用，请点击链接前往续期"), 'color' => '#0000']
            ];
        }elseif($type == 8){
            return $template =[ // 活动主办方收通知
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'keyword2' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                // 'remark' => ['value' => urlencode("如有疑问，请致电".$keyword5."联系我们。"), 'color' => '#0000']
            ];
        }elseif($type == 9) {
            return $template = [ // 分润提醒
                'first' => ['value' => urlencode("您当前已开拓了".$keyword5."个用户！"), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'keyword2' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'remark' => ['value' => urlencode("付费成为节点中心将获得更高收益哦！"), 'color' => '#0000']
            ];
        }elseif($type == 10) {
            return $template =[ // 推荐消费
                'productType' => ['value' => urlencode("商品名"), 'color' => "#0000"],
                'name' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'number' => ['value' => 1, 'color' => '#FF0000'],
                'expDate' => ['value' => '365天', 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }
        elseif($type == 11) {
            return $template =[ // 推荐消费
                'productType' => ['value' => urlencode("商品名"), 'color' => "#0000"],
                'name' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'number' => ['value' => 1, 'color' => '#FF0000'],
                'expDate' => ['value' => '365天', 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }
        elseif($type == 12) {
            return $template =[ // 推荐消费
                'productType' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'DateTime' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'Location' => ['value' => $keyword3, 'color' => '#FF0000'],
                'EventDesc' => ['value' => $keyword4, 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }
        elseif($type == 13) {
            return $template =[ // 提现申请
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'keyword2' => ['value' => $keyword3, 'color' => '#FF0000'],
                'keyword3' => ['value' => $keyword4, 'color' => '#FF0000'],
                'keyword4' => ['value' => date('Y-m-d H:i:s'), 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }
        elseif($type == 14) {
            if($keyword4=='审核通过'){
                $color = '#0000FF';
            }else{
                $color = '#FF0000';
            }
            return $template = [ // 帖子审核模板消息内容
                'first' => ['value' => urlencode($keyword1), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword2), 'color' => '#0000'],
                'keyword2' => ['value' => $keyword3, 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword4), 'color' => $color],
                'keyword4' => ['value' => urlencode($keyword5), 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        }
        elseif($type == 15) {
            return $template = [ // 提问到期
                'first' => ['value' => urlencode("您好，您发起的提问已过期"), 'color' => "#0000"],
                'keyword1' => ['value' => urlencode($keyword1), 'color' => '#0000'],
                'keyword2' => ['value' => $keyword2, 'color' => '#0000'],
                'remark' => ['value' => urlencode("如有疑问，请致电13728427631联系我们。"), 'color' => '#0000']
            ];
        } elseif($type == 16) {
            return $template =[ // 打款成功
                'first' => ['value' => urlencode("打款成功通知"), 'color' => "#0000"],
                'keyword1' => ['value' => $keyword1, 'color' => '#0000'],
                'keyword2' => ['value' => $keyword2, 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                'remark' => ['value' => urlencode("推送成功"), 'color' => '#0000']
            ];
        } elseif($type == 17) {
            return $template =[ // 上门提醒
                'first' => ['value' => urlencode("已成功安排人员上门服务"), 'color' => "#0000"],
                'keyword1' => ['value' => $keyword1, 'color' => '#0000'],
                'keyword2' => ['value' => $keyword2, 'color' => '#0000'],
                'keyword3' => ['value' => urlencode($keyword3), 'color' => '#0000'],
                'keyword4' => ['value' => urlencode($keyword4), 'color' => '#0000'],
                'remark' => ['value' => urlencode("感谢您的耐心等待！"), 'color' => '#0000']
            ];
        }

    }

    public static function templateId($type)
    {
        if ($type == 1) {
            return $template_id = 'eQ7dPSt4oaMxD3rHb5zoW0YgVhYxNyjHb17Qr9o55iA';
        } elseif ($type == 2) {
            return $template_id = 'bQXOWciOhsSzoMUCJB2Mwx9hemyE0yYB6O-t32Dre54';
        } elseif ($type == 3) {
            return $template_id = '-8dWR8dUgFB6FMH72s2OYfIIfNepi9VETHh68U2bgoo';
        } elseif ($type == 4) {
            return $template_id = 'kP89vJvpNzZYcozT07PAwMDFFBzQYny01NsWlZw07j0';
        } elseif ($type == 5) {
            return $template_id = '6xxxEvgoxdJpEaQlqv0vXMA62MDKfRWtZFTZOIwmN_s';
        } elseif ($type == 6) {
            return $template_id = '6xxxEvgoxdJpEaQlqv0vXMA62MDKfRWtZFTZOIwmN_s';
        } elseif ($type == 7) {
            return $template_id = 'nhoKA_AHx7mlpN4sroY3LsI-OwZIPBxe95sioitOOzU';
        } elseif ($type == 8) {
            return $template_id = 'Wal1gNuIaMKQQR5yM60lZ7QX-Gpsj5kWvmm6f6o1sg0';
        } elseif ($type == 9) {
            return $template_id = 'Q6MBa9Zd5aGD9R3HhlgxZ6eCCpgNXbdM1QTFvwGDXTE';
        } elseif ($type == 10) {
            return $template_id = 'eQ7dPSt4oaMxD3rHb5zoW0YgVhYxNyjHb17Qr9o55iA';
        }elseif ($type == 11) {
            return $template_id = 'eQ7dPSt4oaMxD3rHb5zoW0YgVhYxNyjHb17Qr9o55iA';
        }elseif ($type == 12) {
            return $template_id = 'l68QXTfTCDlo3Pw7Z-eWHOe5eLouAn0_KhVS2bET834';
        }elseif ($type == 13) {
            return $template_id = '8Mq3YEDSQhXjCiGA4u56QhmDTUU-1f_nTRIeNMp_cQg';
        }elseif ($type == 14) {
            return $template_id = 'ElE16PM21EouvOdGSPcPBAiNqzbjaUcAi-qpTGn_Zok';
        }elseif ($type == 15) {
            return $template_id = '1YsnsorSc4Kqs1Mx1vuBLVDc9dkae__dFg79jH-tzVk';
        }elseif ($type == 16) {
            return $template_id = 'Qxcc36hdTSYkd4LJW-oNgJqrhhViij9tceIa2_l0x88';
        }elseif ($type == 17) {
            return $template_id = 'nqnUqvsHJdpaHZ_TPb1CU_bGNP7LwqEo3ImjKrgB92I';
        }
    }

}
